package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;

@Service
public class ArticleDetailService {
    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;



    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleService apArticleService;

    public void createStaticUrl(String apArticleContent,long articleId) throws Exception {
        //获取文章内容 然后判断文章的内容

        if (apArticleContent != null && !StringUtils.isBlank(apArticleContent)){
            //2.文章内容通过freemarker生成html文件
            StringWriter out = new StringWriter();
            Template template = configuration.getTemplate("article.ftl");
            HashMap<String, Object> params = new HashMap<>();
            params.put("content", JSONArray.parseArray(apArticleContent));

            template.process(params,out);
            InputStream is = new ByteArrayInputStream(out.toString().getBytes());

            //3.把html文件上传到minio中去
            String path = fileStorageService.uploadHtmlFile("", articleId + ".html", is);
            //4.修改ap_article表,保存static_url字段
            ApArticle apArticle = new ApArticle();
            apArticle.setId(articleId);
            apArticle.setStaticUrl(path);
            apArticleMapper.updateById(apArticle);
        }
    }
}
